import pymysql


class MyORM:
    def __init__(self):
        conn = pymysql.connect(
            host='127.0.0.1',
            port=3306,
            user='root',
            password='123456',
            database='mumushouji',
            charset='utf8',
            autocommit=True,
            cursorclass=pymysql.cursors.DictCursor
        )
        cursor = conn.cursor()
        self.cursor = cursor

    def execute(self, sql):
        self.cursor.execute(sql)
        return self.cursor.fetchall()


class User:
    table_name = 'user'

    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            self.__setattr__(k, v)

    def query_one(self, fields=None, conditions=None):
        if fields and isinstance(fields, list):
            query_fields = ', '.join(fields)
        else:
            query_fields = '*'

        sql = 'select %s from %s' % (query_fields, self.table_name)

        if conditions and isinstance(conditions, dict):
            conditions_lt = [
                "%s='%s'" % (k, v)
                for k, v in conditions.items()
            ]
            sql += ' where ' + ' and '.join(conditions_lt)
        sql += ' limit 1'
        return MyORM().execute(sql)

    def insert(self):
        keys = self.__dict__.keys()
        values = self.__dict__.values()
        sql = 'insert into %s(%s) values("%s")' % (self.table_name, ','.join(keys), '","'.join(values))
        print(sql)
        return MyORM().execute(sql)


if __name__ == '__main__':
    from icecream import ic

    user = User()
    r = user.query_one(['user_id', 'username', 'nickname'], {'user_id': 3, 'username':'3@qq.com'})
    # r = user.query_one()
    ic(r)
